var app = getApp();
var ajax = require('../../utils/ajax.js');
var util = require('../../utils/util.js');
var wxUtil = require('../../utils/wxUtil.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dataLoaded: false,
    myHidden: true,
    modalHidden: true,
    hideDel: false,
    isNotAny: false,
    addrList: [],
    addressId: "",
    name: '',
    tel: '',
    addr: '',
    province: '',
    city: '',
    county: '',
    provinceId: "",
    cityId: "",
    countyId: "",
    value: [0, 0, 0],
    values: [0, 0, 0],
    provinces: [],
    citys: [],
    countys: [],
    province_id: [],
    city_id: [],
    county_id: [],
    province_name: [],
    city_name: [],
    county_name: [],
    goodsId: '',
    skuId: '',
    amount: '',
    cartId: ''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    for (var i in options) {
      if (options.cartId) {
        this.setData({
          goodsId: JSON.parse(options.goodsId),
          skuId: JSON.parse(options.skuId),
          amount: JSON.parse(options.amount),
          cartId: JSON.parse(options.cartId),
          shop: app.getShop(),
        })

      } else {
        this.setData({
          goodsId: JSON.parse(options.goodsId),
          skuId: JSON.parse(options.skuId),
          amount: JSON.parse(options.amount),
          shop: app.getShop(),
          cartId: 0
        })
      }
    }
    this._initAddr('isOnload');
    this.provinces();
    this.citys(110000);
    this.countys(110000, 110100)
  },
  onShareAppMessage: function () {
    return {
      title: this.data.shop.shareTitle,
      path: "pages/index/index"
    }
  },
  /**
   * 省市区开
   */
  _open: function () {
    this.setData({
      condition: true
    })
  },
  /**
  * 省市区关闭
  */
  _close: function () {
    this.setData({
      condition: false
    })
  },
  /**
   * 初始化地址列表
   */
  _initAddr: function (isOnload) {
    var _self = this;
    ajax.P('/openapi/CAddress/getAll', {}, function (data) {
      var d = data.result;
      console.log(data);
      if (d.data) {
        _self.setData({
          addrList: d.data,
          isNotAny: false
        })
      } else if (d.length == 0) {
        if (isOnload) {
          _self.showZanTopTips('您还没有添加收货地址哦,赶紧添加吧');
          _self.setData({
            addrList: d,
            myHidden: false,
            hideDel: true,
            isNotAny: true
          })
        } else {
          _self.setData({
            addrList: d,
            isNotAny: true
          })
        }

      }
      var addrList = _self.data.addrList;
      addrList.some(function (item) {
        if (item.isDefault == 1) {
          item.selected = true;
          _self.setData({
            addrList,
          })
        }
      })
    })
    _self.setData({
      dataLoaded: true
    })
  },
  /**
   * 地址保存 
   */
  _submit: function (e) {
    var _self = this;
    _self.showModal(e.detail.value);
    if (_self.data.modalHidden) {
      _self.setData({
        dataLoaded: false,
        name: e.detail.value.userName,
        tel: e.detail.value.telPhone,
        addr: e.detail.value.addr
      })
      var addressId = this.data.addressId;
      var addrList = this.data.addrList;
      if (this.data.addressId != '') {
        _self.handleAddr(addressId);
      } else {
        if (_self.data.addrList.length == 0) {
          _self.handleAddr('', 1);
        } else {
          _self.handleAddr();
        }
      }
      if (_self.data.goodsId != '') {
        setTimeout(function () {
          wx.redirectTo({
            url: '../../pages/confirmOrder/confirmOrder?goodsId=' + _self.data.goodsId + '&skuId=' + _self.data.skuId + '&amount=' + _self.data.amount + '&cartId=' + _self.data.cartId + '&addressId=' + _self.data.addressId
          })
        }, 500)
      }
      if (_self.data.condition) {
        _self._close();
      }
    }
    _self.setData({
      dataLoaded: true
    })

  },
  /**
   * 绑定表单输入
   */
  _setName: function (e) {
    var _self = this;
    var name = e.detail.value;
    _self.setData({
      name: name
    })
  },
  _setTel: function (e) {
    var _self = this;
    var tel = e.detail.value;
    _self.setData({
      tel: tel
    })
  },
  proCityCounty: function (e) {
    this.setData({
      proCityCounty: e.detail.value
    })
  },
  _setAddr: function (e) {
    var _self = this;
    var addr = e.detail.value;
    _self.setData({
      addr: addr
    })
  },
  /**
   * 添加地址
   */
  _add: function () {
    var _self = this;
    _self.setData({
      myHidden: false,
      addressId: '',
      name: '',
      tel: '',
      addr: '',
      hideDel: true,
      province: '北京市',
      city: '市辖区',
      county: '东城区'
    })
  },
  /**
   * 取消添加地址
   */
  _cancel: function () {
    var _self = this;
    _self.setData({
      myHidden: true
    })
    if (_self.data.condition) {
      _self.close();
    }
  },
  /**
   * 编辑地址
   */
  _edit: function (e) {
    var index = parseInt(e.currentTarget.dataset.index);
    var addrList = this.data.addrList;
    var _self = this;
    _self.setData({
      myHidden: false,
      hideDel: false,
      addressId: addrList[index].id,
      name: addrList[index].reName,
      tel: addrList[index].rePhone,
      addr: addrList[index].detailAddr,
      province: addrList[index].provinceName,
      city: addrList[index].cityName,
      county: addrList[index].districtName
    })
  },
  /**
   * 删除地址
   */
  _del: function () {
    var _self = this;
    _self.setData({
      dataLoaded: false,
    })
    ajax.G(
      '/openapi/CAddress/del',
      {
        id: _self.data.addressId
      },
      function (data) {
        _self.setData({
          myHidden: true
        })
        _self._initAddr();
      }
    )
    if (_self.data.condition) {
      _self.close();
    }

  },
  /**
   * 设置默认值
   */
  _selectDefault: function (e) {
    var _self = this;
    var index = parseInt(e.currentTarget.dataset.index);
    var addrList = this.data.addrList;
    _self.setData({
      addressId: addrList[index].id,
    })
    ajax.G(
      '/openapi/CAddress/setDefault',
      {
        id: _self.data.addressId
      },
      function (data) {
        _self._initAddr();
      })
  },
  /**
   * 关闭模态框
   */
  _hideModal: function () {
    this.setData({
      modalHidden: true
    })
  },
  /**
   * 请求省数据
   */
  provinces: function () {
    this.setData({
      province_id: []
    })
    var _self = this;
    ajax.G(
      '/openapi/CAddress/getAllProvince',
      {},
      function (data) {
        var province_id = _self.data.province_id;
        var province_name = _self.data.province_name;
        var d = data.result;

        _self.setData({
          provinces: d.data
        })
        for (var i = 0; i < _self.data.provinces.length; i++) {
          province_id.push(_self.data.provinces[i].region_id);
          province_name.push(_self.data.provinces[i].region_name);
        }
        _self.setData({
          province_id: province_id,
          province_name: province_name,
          province: province_name[0],
          provinceId: province_id[0]
        });
      }
    );
  },
  /**
   * 请求市数据
   */
  citys: function (province_id) {
    this.setData({
      city_id: []
    })
    var _self = this;

    ajax.G(
      '/openapi/CAddress/getAllCity',
      { province_id: province_id },
      function (data) {

        var city_id = _self.data.city_id;
        var city_name = _self.data.city_name;
        var city = _self.data.city;
        var d = data.result;

        _self.setData({
          citys: d.data
        })
        for (var i = 0; i < _self.data.citys.length; i++) {
          city_id.push(_self.data.citys[i].region_id);
          city_name.push(_self.data.citys[i].region_name);
        }
        _self.setData({
          city_id: city_id,
          city_name: city_name,
          city: city_name[0],
          cityId: city_id[0]
        });
      }
    );
  },

  /**
   * 请求区数据
   */
  countys: function (province_id, city_id) {
    var _self = this;

    ajax.G(
      '/openapi/CAddress/getAllDistrict',
      {
        province_id: province_id,
        city_id: city_id,
      },
      function (data) {
        var county_id = _self.data.county_id;
        var county_name = _self.data.county_name;
        var d = data.result;

        _self.setData({
          countys: d.data
        })
        for (var i = 0; i < _self.data.countys.length; i++) {
          county_id.push(_self.data.countys[i].region_id);
          county_name.push(_self.data.countys[i].region_name)
        }
        _self.setData({
          county_id: county_id,
          county_name: county_name,
          county: county_name[0],
          countyId: county_id[0]
        });
      }
    );
  },
  /**
   * 切换省市区
   */
  bindChange: function (e) {
    var val = e.detail.value;
    var t = this.data.values;
    if (val[0] != t[0]) {
      var _self = this;
      var province_id = this.data.province_id;
      var province = this.data.province_name[val[0]];
      var provinceId = province_id[val[0]]
      this.setData({
        city_id: [],
        city_name: [],
        city: "",
        county_id: [],
        county_name: [],
        county: ""
      })
      ajax.G('/openapi/CAddress/getAllCity', { province_id: provinceId }, function (data) {
        // success
        var city_id = _self.data.city_id;
        var city_name = _self.data.city_name;
        var d = data.result;
        _self.setData({
          citys: d.data
        })
        console.log(d.data)
        for (var i = 0; i < _self.data.citys.length; i++) {
          city_id.push(_self.data.citys[i].region_id);
          city_name.push(_self.data.citys[i].region_name);
        }
        _self.setData({
          city_id: city_id,
          city_name: city_name,
          city: city_name[0],
          cityId: city_id[0]
        });
        _self.countys(provinceId, city_id[0])
      })

      this.setData({
        province: this.data.province_name[val[0]],
        city: this.data.city_name[val[1]],
        county: this.data.county_name[val[2]],
        provinceId: this.data.province_id[val[0]],
        cityId: this.data.cityId,
        countyId: this.data.countyId,
        values: val,
        value: [val[0], 0, 0]
      })
      return;
    }
    if (val[1] != t[1]) {
      var _self = this;
      var province_id = this.data.province_id[val[0]];
      var province = this.data.province_name[val[0]];
      var city_id = _self.data.city_id[val[1]];
      var city = _self.data.city_name[val[1]];
      this.setData({
        county_id: [],
        county_name: [],
        county: ""
      })
      ajax.G('/openapi/CAddress/getAllDistrict', { province_id: province_id, city_id: city_id }, function (data) {
        // success
        var county_id = _self.data.county_id;
        var county_name = _self.data.county_name;
        var d = data.result;
        _self.setData({
          countys: d.data
        })
        console.log(d.data)
        for (var i = 0; i < _self.data.countys.length; i++) {
          county_id.push(_self.data.countys[i].region_id);
          county_name.push(_self.data.countys[i].region_name);
        }
        _self.setData({
          county_id: county_id,
          county_name: county_name,
          county: county_name[0],
          countyId: county_id[0]
        });
      })
      this.setData({
        city: this.data.city_name[val[1]],
        cityId: this.data.city_id[val[1]],
        county: this.data.county_name[val[2]],
        countyId: this.data.county_id[val[2]],
        values: val,
        value: [val[0], val[1], 0]
      })
      return;
    }
    if (val[2] != t[2]) {
      this.setData({
        county: this.data.county_name[val[2]],
        countyId: this.data.county_id[val[2]],
        values: val,
        value: [val[0], val[1], val[2]]
      })
      return;
    }
  },
  handleAddr: function (addressId, isDefault) {
    var _self = this;
    ajax.P(
      '/openapi/CAddress/edit',
      {
        name: this.data.name,
        phone: this.data.tel,
        detailAddr: this.data.addr,
        provinceId: this.data.provinceId,
        cityId: this.data.cityId,
        districtId: this.data.countyId,
        id: addressId,
        isDefault: isDefault
      },
      function (data) {
        _self.setData({
          addressId: data.result.id,
          myHidden: true,
        })
        _self._initAddr();
        util.showOK('保存成功');

      }
    )
  },
  /**
   * 验证输入消息
   */
  showModal: function (inputValue) {
    var regTel = /^1[34578]\d{9}$/;
    var regTel = regTel.exec(inputValue.telPhone);
    if (inputValue.userName.length == 0) {
      this.setData({
        title: "收货人不能为空",
        modalHidden: false
      })
      return false;
    } else if (inputValue.userName.length > 20) {
      this.setData({
        title: "收货人不能超过20位"
      })
      return false;
    } else if (inputValue.telPhone.length == 0) {
      this.setData({
        title: "请输入手机号",
        modalHidden: false
      })
      return false;
    } else if (!regTel) {
      this.setData({
        title: "您输入的手机号格式不正确",
        modalHidden: false
      })
      return false;
    } else if (inputValue.addr.length == 0) {
      this.setData({
        title: "请输入您的详细地址",
        modalHidden: false
      })
      return false;
    } else if (inputValue.addr.length > 100) {
      this.setData({
        title: "您输入的地址长度不能超过100位",
        modalHidden: false
      })
      return false;
    }
    return true;
  },
  showZanTopTips(content = '', options = {}) {
    var zanTopTips = this.data.zanTopTips || {};
    // 如果已经有一个计时器在了，就清理掉先
    if (zanTopTips.timer) {
      clearTimeout(zanTopTips.timer);
      zanTopTips.timer = undefined;
    }

    if (typeof options === 'number') {
      options = {
        duration: options
      };
    }

    // options参数默认参数扩展
    options = Object.assign({
      duration: 1000
    }, options);

    // 设置定时器，定时关闭topTips
    var timer = setTimeout(() => {
      this.setData({
        'zanTopTips.show': false,
        'zanTopTips.timer': undefined
      });
    }, options.duration);

    // 展示出topTips
    this.setData({
      zanTopTips: {
        show: true,
        content,
        options,
        timer
      }
    });
  }
})